import dayjs from "dayjs";
import weekday from 'dayjs/plugin/weekday';

dayjs.extend(weekday);

/**
 * @params year {string | number} 年 例：2023 '2023'
 * @params month {string | number} 月 例：12 '12'
 */


const getCalendar = (year?: number, month?: number) => {

    const currentYear = year || new Date().getFullYear();
    const currentMonth = month || (new Date().getMonth() + 1);

    // 获取该月最后一天的日期，也是本月总天数
    const lastDay = new Date(currentYear, currentMonth, 0).getDate();
    // 一天24小时转换成毫秒数
    const ms24 = 24 * 60 * 60 * 1000;

    // 每个月的日期列表
    const daysArr = [];
    for (let i = 1; i <= lastDay; i++) {
        const mask = `${currentYear}/${currentMonth < 10 ? ('0' + currentMonth) : currentMonth}/${i < 10 ? ('0' + i) : i}`;
        daysArr.push({
            date: mask,
            day: i,
            week: new Date(mask).getDay() || 7,
            isNowMonth: true, // 该日期是否为本月的日期
        });
    }

    // 获取每个月第一天是周几
    const week = new Date(`${currentYear}/${currentMonth}/01`).getDay() || 7;

    // 当月第一周的天数如果不满，就用上个月的日期来补充
    const preWeek = [];
    if (week !== 1) {
        // 获取该月第一天的时间戳
        const timeStamp = new Date(`${currentYear}/${currentMonth}/01`).getTime();

        for (let i = 1; i < week; i++) {
            const mask = timeStamp - ms24 * i;
            preWeek.unshift({
                date: dayjs(mask).format('YYYY/MM/DD'),
                day: parseInt(dayjs(mask).format('D')),
                week: week - i,
                isNowMonth: false,
            })
        }
    }

    // 获取每个月最后一天是周几
    const weekEnd = new Date(`${currentYear}/${currentMonth}/0${lastDay}`).getDay() || 7;

    // 当月最后一周的天数如果不满，就用下个月的日期来补充
    const nextWeek = [];
    if (weekEnd !== 7) {
        // 该月最后一天的时间戳
        const timeStamp = new Date(`${currentYear}/${currentMonth}/0${lastDay}`).getTime();
        for (let i = weekEnd + 1; i <= 7; i++) {
            const mask = timeStamp + ms24 * (i - weekEnd);
            nextWeek.push({
                date: dayjs(mask).format('YYYY/MM/DD'),
                day: parseInt(dayjs(mask).format('D')),
                week: i,
                isNowMonth: false,
            })
        }
    }

    const calenderList = [...preWeek, ...daysArr, ...nextWeek];


    return calenderList;
}

export default getCalendar;